package com.jwsoft.manager.core.integration.impl;

import cn.hutool.core.convert.Convert;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bifang.engine.assistant.core.annotation.ApiService;
import com.bifang.engine.assistant.core.annotation.OpApi;
import com.bifang.engine.assistant.core.annotation.SaveOplog;
import com.bifang.engine.assistant.core.enums.AuTypeEnum;
import com.bifang.engine.assistant.core.enums.BoolEnum;
import com.bifang.engine.assistant.core.enums.FuncTypeEnum;
import com.bifang.engine.assistant.core.exception.AppException;
import com.bifang.engine.data.core.util.PagerUtil;
import com.bifang.module.base.common.vo.dict.SelectVO;
import com.bifang.module.system.core.dao.service.SysDictService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jwsoft.manager.common.vo.eduMessageModelParams.EduMessageModelParamsQueryVO;
import com.jwsoft.manager.common.vo.eduMessageModelParams.EduMessageModelParamsVO;
import com.jwsoft.manager.common.vo.eduSendMessageModel.EduSendMessageModelKeyVO;
import com.jwsoft.manager.common.vo.eduSendMessageModel.EduSendMessageModelQueryVO;
import com.jwsoft.manager.common.vo.eduSendMessageModel.EduSendMessageModelVO;
import com.jwsoft.manager.core.dao.model.EduMessageModelParams;
import com.jwsoft.manager.core.dao.model.EduSendMessageModel;
import com.jwsoft.manager.core.dao.service.EduMessageModelParamsService;
import com.jwsoft.manager.core.dao.service.EduSchoolService;
import com.jwsoft.manager.core.dao.service.EduSendMessageModelService;
import com.jwsoft.manager.core.integration.EduSendMessageModelIntegration;
import com.jwsoft.manager.core.util.EduHelper;
import jodd.util.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.lang.reflect.Field;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * 发送短信内容模板业务实现类
 *
 * @author zjl
 * @since 2024-06-24
 */
@ApiService(funcCode = "eduSendMessageModel", title = "发送短信内容模板")
public class EduSendMessageModelIntegrationImpl implements EduSendMessageModelIntegration {

    @Autowired
    public EduSendMessageModelService eduSendMessageModelService;
    @Autowired
    public EduHelper eduHelper;
    @Autowired
    public EduMessageModelParamsService eduMessageModelParamsService;
    @Autowired
    public SysDictService sysDictService;
    @Autowired
    public EduSchoolService eduSchoolService;

    @Override
    @OpApi(funcCode = "eduSendMessageModel0001", title = "发送短信内容模板分页查询", funcType = FuncTypeEnum.query, checkPrivilege = BoolEnum.FALSE)
    public PageInfo<EduSendMessageModelVO> getList(EduSendMessageModelQueryVO vo) {
        // 开启分页
        if (vo.getPageNum() == null || vo.getPageSize() == null) {
            //如果不传入分页参数，默认最大取1000条
            vo.setPageNum(1);
            vo.setPageSize(1000);
        }
        PageHelper.startPage(vo.getPageNum(), vo.getPageSize());
        QueryWrapper<EduSendMessageModel> queryWrapper = new QueryWrapper<>();
        if (!ObjectUtils.isEmpty(vo.getYear())) {
            queryWrapper.lambda().eq(EduSendMessageModel::getYear, vo.getYear());
        }
        if (StringUtil.isNotBlank(vo.getMessageModelNum())) {
            queryWrapper.lambda().eq(EduSendMessageModel::getMessageModelNum, vo.getMessageModelNum());
        }
        List<EduSendMessageModel> list = eduSendMessageModelService.list(queryWrapper);
        if (CollectionUtils.isEmpty(list)) {
            // 判断是否为空，为空则返回空参数
            return PagerUtil.createEmptyPagerInfo(vo.getPageNum(), vo.getPageSize());
        }
        // 不为空则获取分页结果
        PageInfo<EduSendMessageModel> pageInfo = new PageInfo<>(list);
        // 返回参数需要通过common层的vo实体类，用该方法可以批量转换
        List<EduSendMessageModelVO> resultList = Convert.toList(EduSendMessageModelVO.class, pageInfo.getList());
        // 转义数据字典值
        // dictHelper.valueToName(resultList, Arrays.asList(DemoDictEnum.values()));
        return PagerUtil.parsePagerVo(resultList, pageInfo);
    }

    @Override
    @OpApi(funcCode = "eduSendMessageModel0002", title = "发送短信内容模板根据主键查询详情", funcType = FuncTypeEnum.query, checkPrivilege = BoolEnum.FALSE)
    public EduSendMessageModelVO getById(EduSendMessageModelKeyVO vo) {
        EduSendMessageModel entity = eduSendMessageModelService.getById(vo.getMessageModelId());
        if (ObjectUtils.isEmpty(entity)) {
            throw new AppException("查询不到详细信息!");
        }
        EduSendMessageModelVO result = Convert.convert(EduSendMessageModelVO.class, entity);
        return result;
    }

    /**
     * 保存前统一校验
     */
    @Override
    @OpApi(funcCode = "eduSendMessageModel0003", title = "发送短信内容模板保存前校验", funcType = FuncTypeEnum.other, checkPrivilege = BoolEnum.FALSE)
    public void checkSave(EduSendMessageModelVO vo) {
        //主键为空为新增校验
        if (StringUtil.isBlank(vo.getMessageModelContent())) {
            throw new AppException("模板内容不能为空");
        }
        if (StringUtil.isBlank(vo.getMessageModelNum())) {
            throw new AppException("模板编号不能为空");
        }
        if (vo.getYear() == null) {
            throw new AppException("年份不能为空");
        }
        if (StringUtil.isBlank(vo.getMessageModelId())) {
            LambdaQueryWrapper<EduSendMessageModel> eq = new QueryWrapper<EduSendMessageModel>().lambda()
                    .eq(EduSendMessageModel::getMessageModelNum, vo.getMessageModelNum())
                    .eq(EduSendMessageModel::getYear, eduHelper.thisYear());
            if (eduSendMessageModelService.count(eq) > 0) {
                throw new AppException("当前年度模板编号已存在");
            }
        }
        //主键不为空为修改校验
    }

    @Override
    @OpApi(funcCode = "eduSendMessageModel0004", title = "发送短信内容模板新增", funcType = FuncTypeEnum.insert)
    @SaveOplog(
            operationType = "eduSendMessageModel0004",
            operationName = "发送短信内容模板新增",
            dataType = "messageModelId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public EduSendMessageModelVO add(EduSendMessageModelVO vo) {
        if (vo.getYear() == null) {
            vo.setYear(eduHelper.thisYear());
        }
        //保存前校验
        checkSave(vo);
        //保存数据
        EduSendMessageModel entity = Convert.convert(EduSendMessageModel.class, vo);
        eduSendMessageModelService.save(entity);
        //将主键设置回vo使操作日志可以取到
        vo.setMessageModelId(entity.getMessageModelId());
        return vo;
    }

    @Override
    @OpApi(funcCode = "eduSendMessageModel0005", title = "发送短信内容模板修改", funcType = FuncTypeEnum.update)
    @SaveOplog(
            operationType = "eduSendMessageModel0005",
            operationName = "发送短信内容模板修改",
            dataType = "messageModelId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public EduSendMessageModelVO edit(EduSendMessageModelVO vo) {
        if (ObjectUtils.isEmpty(vo.getMessageModelId())) {
            throw new AppException("传入需要修改的主键不能为空!");
        }
        EduSendMessageModel oldEntity = eduSendMessageModelService.getById(vo.getMessageModelId());
        if (ObjectUtils.isEmpty(oldEntity)) {
            throw new AppException("查询不到需要修改的信息!");
        }
        //保存前校验
        checkSave(vo);
        //保存数据
        EduSendMessageModel entity = Convert.convert(EduSendMessageModel.class, vo);
        eduSendMessageModelService.updateById(entity);
        return vo;
    }

    @Override
    @OpApi(funcCode = "eduSendMessageModel0006", title = "发送短信内容模板根据主键删除", funcType = FuncTypeEnum.delete)
    @SaveOplog(
            operationType = "eduSendMessageModel0006",
            operationName = "发送短信内容模板删除",
            dataType = "messageModelId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public void del(EduSendMessageModelKeyVO vo) {
        if (ObjectUtils.isEmpty(vo.getMessageModelId())) {
            throw new AppException("传入需要删除的数据主键不能为空!");
        }
        EduSendMessageModel entity = eduSendMessageModelService.getById(vo.getMessageModelId());
        if (ObjectUtils.isEmpty(entity)) {
            throw new AppException("未找到需要删除的信息!");
        }
        eduSendMessageModelService.removeById(vo.getMessageModelId());
    }

    @Override
    @OpApi(funcCode = "eduSendMessageModel0007", title = "查询模板参数", funcType = FuncTypeEnum.query)
    public PageInfo<EduMessageModelParamsVO> getModelParams(EduMessageModelParamsQueryVO vo) {
        // 开启分页
        if (vo.getPageNum() == null || vo.getPageSize() == null) {
            //如果不传入分页参数，默认最大取1000条
            vo.setPageNum(1);
            vo.setPageSize(1000);
        }
        PageHelper.startPage(vo.getPageNum(), vo.getPageSize());
        QueryWrapper<EduMessageModelParams> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(EduMessageModelParams::getYear, eduHelper.thisYear());
        List<EduMessageModelParams> list = eduMessageModelParamsService.list(queryWrapper);
        if (CollectionUtils.isEmpty(list)) {
            // 判断是否为空，为空则返回空参数
            return PagerUtil.createEmptyPagerInfo(vo.getPageNum(), vo.getPageSize());
        }
        // 不为空则获取分页结果
        PageInfo<EduMessageModelParams> pageInfo = new PageInfo<>(list);
        // 返回参数需要通过common层的vo实体类，用该方法可以批量转换
        List<EduMessageModelParamsVO> resultList = Convert.toList(EduMessageModelParamsVO.class, pageInfo.getList());
        // 转义数据字典值
        // dictHelper.valueToName(resultList, Arrays.asList(DemoDictEnum.values()));
        return PagerUtil.parsePagerVo(resultList, pageInfo);
    }

    @Override
    public <T> String getHandlerSMS(String eduSendMessageModelNum,T t) {
        if (StringUtils.isBlank(eduSendMessageModelNum)) {
            throw new AppException("模板编号不能为空");
        }
        LambdaQueryWrapper<EduSendMessageModel> modelLambdaQueryWrapper = new QueryWrapper<EduSendMessageModel>().lambda().eq(EduSendMessageModel::getMessageModelNum, eduSendMessageModelNum)
                .eq(EduSendMessageModel::getYear, eduHelper.thisYear());
        EduSendMessageModel messageModel = eduSendMessageModelService.getOne(modelLambdaQueryWrapper, false);
        if (messageModel == null) {
            throw new AppException("查询不到该短信模板");
        }
        String messageModelContent = messageModel.getMessageModelContent();
        if (StringUtils.isBlank(messageModelContent)) {
            throw new AppException("短信模板内容未配置");
        }
        if (ObjectUtils.isEmpty(t)){
            throw new AppException("传入对象参数不能为空");
        }
        String mailText = handleMailText(t, messageModelContent);
        return mailText;
    }

    private <T> String handleMailText(T t, String messageModelContent){
        if (StringUtils.isBlank(messageModelContent)){
            throw new AppException("短信模板内容未配置");
        }
        List<SelectVO> areaList = sysDictService.getDictByDictField("AREA");
        Map<String, String> areaMap = areaList.stream().collect(Collectors.toMap(SelectVO::getDictKey, SelectVO::getDictValue));
        HashMap<Integer, String> enrollNum = new HashMap<>();
        enrollNum.put(1,"第一批次");
        enrollNum.put(2,"第二批次");
        enrollNum.put(3,"第三批次");
        Pattern pattern = Pattern.compile("\\$\\{(.+?)\\}");
        Matcher matcher = pattern.matcher(messageModelContent);
        List<String> paramsList = new ArrayList<>();
        while (matcher.find()) {
            paramsList.add(matcher.group(1));
        }
        HashMap<String, Object> hashMap = new HashMap<>();
        Field[] declaredFields = t.getClass().getDeclaredFields();
        HashMap<String, Object> map = new HashMap<>();
        for (Field field : declaredFields){
            field.setAccessible(true);
            Object value;
            try {
                value = field.get(t);
            }catch (Exception e){
                throw new AppException(e);
            }
            String name = field.getName();
            map.put(name,value);
        }
        for (String param : paramsList){
            if (map.containsKey(param)){
                if (map.get(param)==null){
                    throw new AppException(param+"模板个性化参数存在数据为空");
                }
                if (param.equalsIgnoreCase("areaCode")){
                    hashMap.put(param,areaMap.get(map.get(param)));
                }else if (param.equalsIgnoreCase("enrollNum")){
                    hashMap.put(param,enrollNum.get(map.get(param)));
                }else if (param.equalsIgnoreCase("schoolId")){
                    hashMap.put(param,eduSchoolService.getDetail(map.get(param).toString()).getSchoolName());
                } else{
                    hashMap.put(param,map.get(param));
                }
            }
        }
        //短信内容
        String mailText = getMailText(hashMap, messageModelContent);
        return mailText;
    }
    public static String getMailText(java.util.Map<String, Object> map, String htmlTemplate) {
        String htmlText = htmlTemplate;
        Set<String> keys = map.keySet();
        for (Iterator<String> it = keys.iterator(); it.hasNext();) {
            String key = it.next();
            htmlText = htmlText.replace("${" + key + "}", (String) map.get(key));
        }
        return htmlText;
    }
}
